package com.xianzhiOA.controller;

import com.sun.org.apache.bcel.internal.generic.RETURN;
import com.sun.org.apache.xpath.internal.SourceTree;
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.xianzhiOA.bean.XzAttendance;
import com.xianzhiOA.bean.XzEmp;
import com.xianzhiOA.service.XzAttendanceService;
import com.xianzhiOA.service.XzEmpService;
import com.xianzhiOA.util.PageBean;
import org.apache.poi.util.SystemOutLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

//import net.sf.json.JSONArray;


/**
 * Created by Administrator on 2017/4/13.
 */
@Controller
@RequestMapping("/XzAttendance")
public class XzAttendanceController {

    @Autowired
    private XzAttendanceService xzAttendanceService;
    @Autowired
    private XzEmpService xzEmpService;


//    @RequestMapping("selectAll")
//    public ModelAndView selectAll(){
//        ModelAndView mv = new ModelAndView("backEnd/attendanceShow");
//
//        System.out.println("selectAll");
//        return mv;
//    }






//    //添加考勤记录
//    @RequestMapping("/addAttendance")
//    public ModelAndView addAttendance(XzAttendance xzAttendance){
//    ModelAndView mv=new ModelAndView("redirect:selectAll");
//
//    try {
//        xzAttendanceService.insert(xzAttendance);
//        mv.addObject("msg","添加成功");
//    } catch (Exception e) {
//        e.printStackTrace();
//        mv.addObject("msg","添加失败");
//    }
//    return  mv;
//    }
//
//    //删除考勤记录
//    @RequestMapping("/deleteAttendance")
//    public ModelAndView deleteAttendance(long attendanceId){
//        ModelAndView mv=new ModelAndView("redirect:selectAll");
//        Date newDate=new Date();
//        XzAttendance  xzAttendance=new XzAttendance();
//        xzAttendance.setAttendanceId(attendanceId);
//        xzAttendance.setDeleteTime(newDate);
//
//        xzAttendanceService.phoneyDeleteByPrimaryKey(xzAttendance);
//         return  mv;
//    }
//
//    //按ID查询考勤记录(并跳到修改页面)
//    @RequestMapping("attendanceEdit")
//    public ModelAndView attendanceEdit(long attendanceId){
//        ModelAndView mv=new ModelAndView("backEnd/attendanceEdit");
//        XzAttendance xzAttendance=xzAttendanceService.findById(attendanceId);
//        mv.addObject("xzAttendance",xzAttendance);
//        return  mv;
//    }
//
//    //修改考勤表
//    @RequestMapping("updateAttendance")
//    public  ModelAndView updateAttendance(XzAttendance xzAttendance){
//          ModelAndView mv=new ModelAndView("backEnd/attendanceEdit");
//        try {
//            xzAttendanceService.updateByPrimaryKey(xzAttendance);
//            mv.addObject("msg","修改成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//            mv.addObject("msg","修改失败");
//        }
//        return  mv;
//    }
//
    //查询所有（分页功能）
@RequestMapping("selectAll")
    public ModelAndView selectAll(XzAttendance xzAttendance, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int rows, Date begin, Date end,String timeInterval,String empNo) {

       ModelAndView mv=new ModelAndView("backEnd/attendanceShow");
        if(xzAttendance.getXzEmps()==null){
            xzAttendance.setXzEmps(new XzEmp());
        }

    System.out.println("empNo:"+empNo);

        //如果timeInterval没传来值，默认显示此人本月的
        if(timeInterval == null && begin == null && end == null) {
            Date monthFirstDate=xzAttendanceService.getTimesMonthmorning();
            Date monthLastDate=xzAttendanceService.getTimesMonthnight();

            begin=monthFirstDate;
            end=monthLastDate;
        }
        else if(timeInterval != null && begin == null && end == null){
//             if(timeInterval.equals("本周")) {
//                 Date weekFirstDate = xzAttendanceService.getTimesWeekmorning();
//                 Date weekLastDate=xzAttendanceService.getTimesWeeknight();
//
//
//                 begin=weekFirstDate;
//                 end=weekLastDate;
//             }

        }


        PageBean<XzAttendance> pageBean=xzAttendanceService.selAll(xzAttendance,begin,end,page,rows);
        List<XzAttendance> xzAttendanceList=pageBean.getList();




        int count=xzAttendanceList.size();
        //String []first=new String[]{};   //初始化一个添加上班时间的数组
         String[] first = new String[count];
         String[] last=new String [count];
        System.out.println("count:"+count);
        for (int i=0;i<count;i++){
            XzAttendance  attendance  = xzAttendanceList.get(i);
            System.out.println("attendance:"+attendance);
            Date FirstTime=attendance.getFirstTime();
            Date LastTime=attendance.getLastTime();




            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
            String FirstTimeStr="";
            String LastTimeStr="";

            System.out.println("FirstTime:"+FirstTime+",LastTime:"+LastTime);


            if(FirstTime == null && LastTime == null){
                FirstTimeStr="00:00";
                LastTimeStr="00:00";
            }
            if(FirstTime == null){
                FirstTimeStr="00:00";
                LastTimeStr = formatter.format(LastTime);
            }
            if(LastTime == null){
                LastTimeStr="00:00";
                FirstTimeStr=formatter.format(FirstTime);
            }
            else {
                FirstTimeStr=formatter.format(FirstTime);
                LastTimeStr = formatter.format(LastTime);
            }

           // System.out.println("FirstTimeStr:"+FirstTime+",LastTimeStr:"+LastTime);
            first[i]=FirstTimeStr;
            last[i]=LastTimeStr;

        }


    System.out.println("begin:"+begin+",end="+end);

        for (int i=0;i<count;i++){
            System.out.println("第"+i+"个是："+first[i]);
        }

    for (int i=0;i<count;i++) {
        System.out.println("第"+i+"个是："+last[i]);
    }

    String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]" ;  // 一个未转化的字符串

//    JSONArray json = JSONArray.fromObject(str); // 首先把字符串转成 JSONArray  对象
//
//    if(json.size()>0){
//        for(int i=0;i<json.size();i++){
//            JSONObject job = json.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
//            System.out.println(job.get("name")+"=") ;  // 得到 每个对象中的属性值
//        }
//    }



       //  XzAttendance  attendance  = xzAttendanceList.get(0);
        mv.addObject("AttendanceList",xzAttendanceList);
        mv.addObject("Attendance",xzAttendance);
        mv.addObject("page",pageBean.getPageNum());
        mv.addObject("pages",pageBean.getPages());
        mv.addObject("rows",pageBean.getSize());
        mv.addObject("total",pageBean.getTotal());


        mv.addObject("first",first);
        mv.addObject("last",last);
        System.out.println("执行结束,xzAttendance="+xzAttendance);
       return  mv;
    }


    //查询本周和本月的某个人的考勤记录
    @RequestMapping("selectWeekOrmonth")
    public  ModelAndView selectWeekOrMonth(String  parameter){
        ModelAndView mv=new ModelAndView("backEnd/attendanceShow");
        System.out.println(parameter);
        return  mv;
    }

    //跳转到编辑页面
    @RequestMapping("toEditAttendancePage")
    public  ModelAndView toEditAttendancePage(String days,String empNo,String YearAndMonths){

        System.out.println("YearAndMonths:"+YearAndMonths);
        int empNoInt=Integer.parseInt(empNo);
        XzEmp xzEmp= xzEmpService.selByEmpNo(empNoInt);

       int daysInt=Integer.parseInt(days);
        //传来的日期数加0（给1-9的日期前加0）
        if(daysInt>0 && daysInt <10){
            days="0"+days;
        }
        days="-"+days+" ";
        String dataTimeBegin=YearAndMonths+days+"00:00:00";
        String dataTimeEnd=YearAndMonths+days+"23:59:59";

        System.out.println("dataTimeBegin:"+dataTimeBegin+",dataTimeEnd:"+dataTimeEnd);

        //根据选定的开始时间和结束时间和用户编号进行查询(用于判定需添加还是修改)
        SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //Date date = sdf.parse( " 2008-07-10 19:20:00 " );
        Date BeginDate=null;
        Date EndDate=null;
        try {
             BeginDate=sdf.parse(dataTimeBegin);
             EndDate=sdf.parse(dataTimeEnd);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println("BeginDate:"+BeginDate+",EndDate:"+EndDate);
        XzAttendance xzAttendance=new XzAttendance();
           xzAttendance =xzAttendanceService.selectByDayAndEmpNo(BeginDate,EndDate,empNoInt);

           if(xzAttendance == null){
               System.out.println("需添加");
           }else {
               System.out.println("需修改");
           }


        System.out.println("xzEmp:"+xzEmp);
        System.out.println("添加页面的days:"+days+",empNo:"+empNo+",empName"+xzEmp.getEmpName());

         //ModelAndView mv=new ModelAndView("backEnd/attendanceEdit");
        ModelAndView mv=new ModelAndView("backEnd/attendanceEdit");
        mv.addObject("days",days);
        mv.addObject("xzEmp",xzEmp);
         return  mv;
    }




    //单击添加按钮后判断账号是否存在
//    @RequestMapping("checkEmpIdExist")
//    public ModelAndView checkEmpIdExist(){
//         ModelAndView mv=new ModelAndView("");
//
//    }


    //添加考勤记录
    @RequestMapping("/addAttendance")
    public ModelAndView addAttendance(XzAttendance xzAttendance){
    ModelAndView mv=new ModelAndView("redirect:selectAll");

    try {
        xzAttendanceService.insert(xzAttendance);
        mv.addObject("msg","添加成功");
    } catch (Exception e) {
        e.printStackTrace();
        mv.addObject("msg","添加失败");
    }
      return  mv;
    }


    //判断添加时的账号是否存在
    //   public ModelAndView addEmp(@Validated({XzEmp.F2.class}) XzEmp xzEmp, BindingResult result) {
    @RequestMapping("/CheckempAccountExistence")
    public  ModelAndView CheckempAccountExistence(@Validated({XzEmp.F2.class})  XzAttendance xzAttendance,BindingResult result){
        ModelAndView mv=new ModelAndView("backEnd/attendanceEdit");

        System.out.println("xzAttendance："+xzAttendance);

        if(result.hasErrors()){
            //验证错误
            System.out.println("已验证错误");
        }else {
            System.out.println("未验证错误");
        }
        mv = new ModelAndView("backEnd/attendanceEdit");
        return  mv;
    }


    @RequestMapping("attendanceImport.emp")
    public ModelAndView attendanceImport(){
        ModelAndView mv = new ModelAndView("backEnd/attendanceImport");

        return mv;
    }

    @RequestMapping("ToTest")
    public ModelAndView ToTest() {
        ModelAndView mv = new ModelAndView("backEnd/chartTest");
        return mv;
    }




}
